<?php

namespace Users\Register\Helper;

use Users\Profile;
use Users\VkConfig as Config;

/**
 * Регистрация через ВКонтакте
 *
 * @author kosh
 *        
 */
trait Vk {
	
	use \Pinenut\User\OAuth2\Auth;
	function config() {
		$config = Config::get ();
		$config [Config::REDIRECTURL] = 'http://' . $_SERVER ['HTTP_HOST'] . $this->url ( 'users.register.vk' );
		$this->config = $config;
		
		return $config;
	}
	function createAuth($data) {
		// идентификатора пользователя нет, получаем его другим запросом
		$auth = new \Pinenut\User\OAuth2\Vk();
		$auth->accessToken = $data ['access_token'];
		$auth->accessTokenExpired = time () + $data ['expires_in'] == 0 ? 3600 * 24 * 365 : $data ['expires_in'];
		$auth->id = $data ['user_id'];
		
		$this->auth = $auth;
		
		return $auth;
	}
	function profile() {
		$config = $this->config ();
		
		// осуществеление аутетинфикации
		$client = new \OAuth2\Client ( $config [Config::CLIENTID], $config [Config::CLIENTSECRET] );
		
		$client->setAccessToken ( $this->auth->accessToken );
		
		$response = $client->fetch ( 'https://api.vk.com/method/users.get', [ 
				'fields' => 'photo_max_orig, sex, bdate, city, contacts, verified',
				'v' => '5.21' 
		] );
		$result = reset ( $response ['result'] ['response'] );
		
		$this->data = $result;
		
		$profile = new Profile();
		
		$profile->nickname = $this->data ['first_name'];
		//$profile->verified = $this->data ['verified'];
		
		return $profile;
	}
}
